package com.imau.brand.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

@WebServlet("/upload")
@MultipartConfig(
        maxFileSize = 8 * 1024 * 1024,  // 单个文件最大8MB
        maxRequestSize = 10 * 1024 * 1024,  // 整个请求最大10MB
        fileSizeThreshold = 1024 * 1024 // 超过1MB写入磁盘
        // 文件存储路径    private static final String UPLOAD_DIR = "uploads";
)
public class FileUploadServlet extends HttpServlet {

    private static final String UPLOAD_DIR = "uploads";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 创建上传目录
        String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIR;
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        uploadPath = uploadPath + File.separator + format.format(new Date());
        String location = "";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }


        Collection<Part> parts = request.getParts();

        for (Part part : parts) {
            String fileName = getFileName(part);
            String filetype = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (fileName != null && !fileName.isEmpty()) {
                location = uploadPath + "/" + new Date().getTime() + "." + filetype;
                part.write(location);
            }


            // 返回上传文件名
            response.getWriter().write(location.substring(location.lastIndexOf("\\uploads") + 1));
        }

    }

    private String getFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        String[] elements = contentDisposition.split(";");
        for (String element : elements) {
            if (element.trim().startsWith("filename")) {
                return element.substring(element.indexOf("=") + 2, element.length() - 1);
            }
        }
        return null;
    }
}